package rpc

import (
	"github.com/golang/glog"
	"github.com/oikomi/FishChatServer2/common/ecode"
	"github.com/oikomi/FishChatServer2/protocol/rpc"
	"github.com/oikomi/FishChatServer2/server/hall/conf"
	//	"github.com/oikomi/FishChatServer2/server/hall/dao"
	sd "github.com/oikomi/FishChatServer2/service_discovery/etcd"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"net"
)

type RPCServer struct {
	//dao       *dao.Dao
	rpcClient *RPCClient
}

func (s *RPCServer) Login(ctx context.Context, in *rpc.HallLoginReq) (res *rpc.HallLoginRes, err error) {
	glog.Info("hall recive login")
	if in.Token == "" || in.UID < 0 {
		res = &rpc.HallLoginRes{
			ErrCode: ecode.NoToken.Uint32(),
			ErrStr:  ecode.NoToken.String(),
		}
		return
	}

	rgRes, err := s.rpcClient.Register.Login(ctx, in.UID, in.Token, in.AccessAddr)
	if err != nil {
		res = &rpc.HallLoginRes{
			ErrCode: ecode.ServerErr.Uint32(),
			ErrStr:  ecode.ServerErr.String(),
		}
		glog.Error(err)
		return
	}

	res = &rpc.HallLoginRes{
		ErrCode: rgRes.ErrCode,
		ErrStr:  rgRes.ErrStr,
	}
	return
}

func (s *RPCServer) CreateTable(ctx context.Context, in *rpc.CreateTableReq) (res *rpc.CreateTableRes, err error) {
	glog.Info("hall create table")

	ctRes, err := s.rpcClient.Logic.CreateTable(in.UID)
	if err != nil {
		res = &rpc.CreateTableRes{
			ErrCode: ecode.ServerErr.Uint32(),
			ErrStr:  ecode.ServerErr.String(),
		}
		glog.Error(err)
		return
	}

	res = &rpc.CreateTableRes{
		ErrCode:   ctRes.ErrCode,
		ErrStr:    ctRes.ErrStr,
		LogicAddr: ctRes.LogicAddr,
	}
	return
}

func (s *RPCServer) EnterTable(ctx context.Context, in *rpc.EnterTableReq) (res *rpc.EnterTableRes, err error) {
	ctRes, err := s.rpcClient.Manager.GetLogicIDByTableId(ctx, in.TableID)
	if err != nil {
		res = &rpc.EnterTableRes{
			ErrCode: ecode.ServerErr.Uint32(),
			ErrStr:  ecode.ServerErr.String(),
		}
		glog.Error(err)
		return
	}
	res = &rpc.EnterTableRes{
		ErrCode:   ctRes.ErrCode,
		ErrStr:    ctRes.ErrStr,
		LogicAddr: ctRes.LogicAddr,
	}
	return
}

func RPCServerInit(rpcClient *RPCClient) {
	glog.Info("[hall] rpc server init: ", conf.Conf.RPCServer.Addr)
	lis, err := net.Listen(conf.Conf.RPCServer.Proto, conf.Conf.RPCServer.Addr)
	if err != nil {
		glog.Error(err)
		panic(err)
	}
	err = sd.Register(conf.Conf.ServiceDiscoveryServer.ServiceName, conf.Conf.ServiceDiscoveryServer.RPCAddr, conf.Conf.ServiceDiscoveryServer.EtcdAddr, conf.Conf.ServiceDiscoveryServer.Interval, conf.Conf.ServiceDiscoveryServer.TTL)
	if err != nil {
		glog.Error(err)
		panic(err)
	}
	s := grpc.NewServer()
	rpcServer := &RPCServer{
		//dao:       dao.NewDao(),
		rpcClient: rpcClient,
	}
	rpc.RegisterHallRPCServer(s, rpcServer)
	s.Serve(lis)
}
